<template>
  <div class="center">
    <n-card :bordered="false" class="mt-4 proCard" size="small" :segmented="{ content: 'hard' }">
      <div class="formClass">
        <n-form :rules="rules" :model="formValue" :size="size" ref="formRef" label-placement="top">
          <n-space justify="space-between">
            <n-h6 prefix="bar" type="success">企业信息</n-h6>
            <n-space>
              <n-button v-if="type" size="small" @click="edit()">编辑</n-button>
              <n-button v-if="!type" size="small" @click="cancel()">取消</n-button>
              <n-button v-if="!type" type="success" size="small" @click="preservation"
                >保存</n-button
              >
            </n-space>
          </n-space>
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi span="4">
              <n-avatar style="background-color: #18a058; color: white; width: 48px; height: 48px">
                <!-- 处理头像 -->
                {{ formValue && formValue.enterpriseName && formValue.enterpriseName[0] }}
              </n-avatar>
            </n-form-item-gi>
            <n-form-item-gi span="20" label="企业名称" path="enterpriseName">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.enterpriseName }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.enterpriseName" />
            </n-form-item-gi>

            <n-form-item-gi span="12" label="企业法人" path="legalPerson">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.legalPerson }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.legalPerson" />
            </n-form-item-gi>

            <n-form-item-gi span="12" label="法人联系电话" path="legalMobile">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.legalMobile }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.legalMobile" />
            </n-form-item-gi>

            <n-form-item-gi span="12" label="联系人" path="contactPerson">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.contactPerson }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.contactPerson" />
            </n-form-item-gi>

            <n-form-item-gi span="12" label="联系电话" path="contactMobile">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.contactMobile }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.contactMobile" />
            </n-form-item-gi>

            <n-form-item-gi span="12" label="地址" path="address">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.address }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.address" />
            </n-form-item-gi>

            <n-form-item-gi span="12" label="所属行业" path="contactMobile">
              <div v-if="!isEdit" class="detail-item-value">
                <span>
                  {{
                    industryList.length > 0 && industryList[formValue.industryId]['industryName']
                  }}
                  &nbsp;
                </span>
              </div>
              <n-select
                v-if="isEdit"
                v-model:value="formValue.industryId"
                :options="industryList"
              />
            </n-form-item-gi>
            <n-form-item-gi span="12" label="所属协会" path="associationName">
              <div v-if="!isEdit" class="detail-item-value">
                <span>
                  {{
                    associationList.length > 0 &&
                    associationList[formValue.associationId]['associationName']
                  }}
                  &nbsp;
                </span>
              </div>
              <n-select
                v-if="isEdit"
                v-model:value="formValue.associationId"
                :options="associationList"
              />
            </n-form-item-gi>

            <n-form-item-gi span="12" label="区域id" path="districtCode">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.districtCode }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.districtCode" />
            </n-form-item-gi>

            <n-form-item-gi span="12" label="社会信用代码" path="socialCreditCode">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.socialCreditCode }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.socialCreditCode" />
            </n-form-item-gi>

            <n-form-item-gi span="12" label="发证机构" path="associationAgency">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.associationAgency }} &nbsp; </span>
              </div>
              <n-input v-model:value="formValue.associationAgency" />
            </n-form-item-gi>

            <n-form-item-gi span="12" label="许可证有效期" path="associationAgency">
              <div v-if="!isEdit" class="detail-item-value">
                <span>
                  {{ moment(formValue.licenseStart).format('YYYY-MM-DD') }} -
                  {{ moment(formValue.licenseEnd).format('YYYY-MM-DD') }} &nbsp;
                </span>
              </div>
              <n-date-picker
                v-if="isEdit"
                v-model:value="formValue.licenseTimeRange"
                type="daterange"
                clearable
              />
              <!--              <n-date-picker v-if="isEdit" v-model:value="formValue.createTime" type="daterange" clearable />-->
            </n-form-item-gi>

            <n-form-item-gi span="12" label="经营许可证(图片)" path="licenseUri">
              <!--              :size="item.size"-->
              <n-image :style="{ width: '48px' }" :src="formValue.licenseUri" />
              <n-upload :multiple="false" @change="beforeLicenseUpload">
                <n-button>选择文件</n-button>
              </n-upload>
            </n-form-item-gi>
          </n-grid>
        </n-form>
      </div>
    </n-card>
  </div>
</template>

<script>
  import { defineComponent, ref, onMounted, unref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { NConfigProvider, NCascader, NInput, NDatePicker, NSpace } from 'naive-ui';
  import { useRoute } from 'vue-router';
  import { getEnterpriseDetail } from '@/api/BaseInfo';
  import { getAssoicationList, saveEnterprise } from "../../../api/BaseInfo";
  import { fetchIndustryList } from '../../../api/Department';
  import moment from 'moment';

  export default defineComponent({
    components: {
      NConfigProvider,
      NInput,
      NDatePicker,
      NSpace,
    },

    setup() {
      const formRef = ref(null);
      const message = useMessage();
      const route = useRoute();
      const _id = ref(route.params.id);
      const industryList = ref([]);
      const associationList = ref([]);
      const type = ref(true);
      const isEdit = ref(false);
      const ItemList = ref([
        {
          type: 'N-avatar',
          enName: 'enterpriseName',
          span: 4,
          clearable: true,
          size: 'small',
          size: 48,
          src: '',
        },
        {
          label: '企业名称',
          type: 'N-input',
          enName: 'enterpriseName',
          span: 20,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '企业法人',
          type: 'N-input',
          enName: 'legalPerson',
          span: 12,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '法人联系电话',
          type: 'N-input',
          enName: 'legalMobile',
          span: 12,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '联系人',
          type: 'N-input',
          enName: 'contactPerson',
          span: 12,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '联系电话',
          type: 'N-input',
          enName: 'contactMobile',
          span: 12,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '地址',
          type: 'N-input',
          enName: 'address',
          span: 12,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '所属行业',
          type: 'N-select',
          enName: 'industryName',
          span: 12,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '所属协会',
          type: 'N-input',
          enName: 'associationName',
          span: 12,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '区域id',
          type: 'N-input',
          enName: 'districtCode',
          span: 12,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '社会信用代码',
          type: 'N-input',
          enName: 'socialCreditCode',
          span: 12,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '发证机构',
          type: 'N-input',
          enName: 'associationAgency',
          span: 12,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '许可证有效期',
          type: 'N-input',
          enName: 'associationAgency',
          span: 12,
          clearable: true,
          disabled: true,
          size: 'small',
        },
        {
          label: '经营许可证(图片)',
          type: 'N-image',
          enName: 'licenseUri',
          span: 24,
          clearable: true,
          disabled: true,
          size: 'small',
          width: '100px',
          src: 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg',
        },
      ]);
      const formValue = ref({});

      const beforeLicenseUpload = ({ fileList }) => {
        const file = fileList[fileList.length - 1].file;
        formValue.value.licensePhoto = file;
      };
      //编辑
      const edit = () => {
        type.value = false;
        isEdit.value = true;
        ItemList.value.map((res) => {
          return (res.disabled = false);
        });
        console.log(formValue.value);
      };
      //保存
      const preservation = (e) => {
        e.preventDefault();
        formRef.value.validate(async (error) => {
          console.log(formValue.value.licenseTimeRange);
          if (error) return; // 验证失败
          formValue.value.licenseStart = moment(formValue.value.licenseTimeRange[0]).format(
            'YYYY-MM-DD'
          );
          formValue.value.licenseEnd = moment(formValue.value.licenseTimeRange[1]).format(
            'YYYY-MM-DD'
          );
          const keys = Object.keys(formValue.value);
          const formdata = new FormData();
          for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            if (key !== 'createTime' && key !== 'licenseTimeRange' && key !== 'updateTime') {
              formdata.append(key, formValue.value[key]);
            }
          }
          const res = await saveEnterprise(formdata);
          // 保存完成之后重新设置为disabled
          type.value = true;
          isEdit.value = false;
          ItemList.value.map((res) => {
            return (res.disabled = true);
          });
        });
      };
      //取消
      const cancel = () => {
        type.value = true;
        isEdit.value = false;
        ItemList.value.map((res) => {
          return (res.disabled = true);
        });
      };
      // getEnterpriseDetail
      onMounted(async () => {
        const record = await getEnterpriseDetail(_id.value);
        formValue.value = record;
        formValue.value.licenseTimeRange = ref([
          Date.parse(record.licenseStart),
          Date.parse(record.licenseEnd),
        ]);
        record.createTime = Date.parse(record.createTime);
        industryList.value = await fetchIndustryList();
        associationList.value = await getAssoicationList();
        associationList.value = associationList.value.list;
        for (let i = 0; i < associationList.value.length; i++) {
          const item = associationList.value[i];
          associationList.value[i].label = item.associationName;
          associationList.value[i].value = item.id;
        }
        for (let i = 0; i < industryList.value.length; i++) {
          const item = industryList.value[i];
          industryList.value[i].label = item.industryName;
          industryList.value[i].value = item.id;
        }
      });
      return {
        moment,
        beforeLicenseUpload,
        industryList,
        associationList,
        formRef,
        isEdit,
        edit,
        preservation,
        cancel,
        size: ref('medium'),
        ItemList,
        formValue,
        type,
        rules: {
          legalMobile: {
            required: true,
            message: '请输入手机号',
            trigger: ['input'],
          },
          legalPerson: {
            required: true,
            message: '请输入企业法人',
            trigger: ['input'],
          },
          industryId: {
            required: true,
            message: '请选择所属行业',
            trigger: ['input', 'blur'],
          },
          enterpriseName: {
            required: true,
            message: '请输入企业名称',
            trigger: ['input'],
          },
          districtCode: {
            required: true,
            message: '请选择区域',
            trigger: ['input', 'blur'],
          },
          contactPerson: {
            required: true,
            message: '请输入联系人',
            trigger: ['input'],
          },
          contactMobile: {
            required: true,
            message: '请输入联系人手机号',
            trigger: ['input'],
          },
        },
      };
    },
  });
</script>
<style lang="less" scoped>
  .center :deep .n-avatar {
    position: relative;
    bottom: 15px;
  }
  .formClass {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .detail-item-value {
    background-color: #f5f5f5;
    padding: 5px 12px;
    width: 100%;
  }
</style>
